package com.hongxun.budget.ui.activity.sg;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.AMapException;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.maps.offlinemap.OfflineMapManager.OfflineMapDownloadListener;
import com.amap.api.maps.offlinemap.OfflineMapProvince;
import com.amap.api.maps.offlinemap.OfflineMapStatus;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * android api<23
 */
public class myOfflineMapActivity extends BaseActivity implements OfflineMapDownloadListener {

    @BindView(R.id.back_btn)
    ImageButton backBtn;
    @BindView(R.id.center_title)
    TextView centerTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.list)
    ExpandableListView expandableListView;

    @Override
    public int getLayoutId() {
        return R.layout.sg_offlinemap_activity;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        backBtn.setVisibility(View.GONE);
        rightBtn.setVisibility(View.GONE);
        rightSave.setVisibility(View.GONE);
        init();
    }

    private OfflineMapManager amapManager = null;// 离线地图下载控制器
    private List<OfflineMapProvince> provinceList = new ArrayList<>();// 保存一级目录的省直辖市
    private HashMap<Object, List<OfflineMapCity>> cityMap = new HashMap<>();// 保存二级目录的市
    private int completeCode;// 记录下载比例
    private boolean[] isOpen;// 记录一级目录是否打开
    private List<OfflineMapCity> cityList;
    private String cityKey = "CITYKEY";

    /**
     * 初始化UI布局文件
     */
    private void init() {
        cityList = JSON.parseArray(String.valueOf(SPUtils.get(context, cityKey, "")), OfflineMapCity.class);
        if (cityList == null) cityList = new ArrayList<>();
        amapManager = new OfflineMapManager(this, this);
        if (!cityList.isEmpty()) onCheckUpdate(true, cityList.get(0).getCity());
        provinceList = amapManager.getOfflineMapProvinceList();
        List<OfflineMapProvince> bigCityList = new ArrayList<>();// 以省格式保存直辖市、港澳、全国概要图
        List<OfflineMapCity> mapCityList = new ArrayList<>();// 以市格式保存直辖市、港澳、全国概要图
        List<OfflineMapCity> gangaoList = new ArrayList<>();// 保存港澳城市
        List<OfflineMapCity> gaiyaotuList = new ArrayList<>();// 保存概要图
        for (int i = 0; i < provinceList.size(); i++) {
            OfflineMapProvince offlineMapProvince = provinceList.get(i);
            List<OfflineMapCity> city = new ArrayList<>();
            OfflineMapCity aMapCity = getCicy(offlineMapProvince);
            if (offlineMapProvince.getCityList().size() != 1) {
                city.addAll(offlineMapProvince.getCityList());
            } else {
                mapCityList.add(aMapCity);
                bigCityList.add(offlineMapProvince);
            }
            cityMap.put(i + 3, city);
        }
        OfflineMapProvince title = new OfflineMapProvince();
        title.setProvinceName("概要图");
        provinceList.add(0, title);
        title = new OfflineMapProvince();
        title.setProvinceName("直辖市");
        provinceList.add(1, title);
        title = new OfflineMapProvince();
        title.setProvinceName("港澳");
        provinceList.add(2, title);
        provinceList.removeAll(bigCityList);

        for (OfflineMapProvince aMapProvince : bigCityList) {
            if (aMapProvince.getProvinceName().contains("香港") || aMapProvince.getProvinceName().contains("澳门")) {
                gangaoList.add(getCicy(aMapProvince));
            } else if (aMapProvince.getProvinceName().contains("全国概要图")) {
                gaiyaotuList.add(getCicy(aMapProvince));
            }
        }
        if (mapCityList.size() > 4) {
            List<OfflineMapCity> subList = mapCityList.subList(0, 4);
            cityMap.put(1, subList);// 在HashMap中第1位置添加直辖市
        } else {
            cityMap.put(1, mapCityList);// 在HashMap中第1位置添加直辖市
        }
        cityMap.put(0, gaiyaotuList);// 在HashMap中第0位置添加全国概要图

        cityMap.put(2, gangaoList);// 在HashMap中第2位置添加港澳
        isOpen = new boolean[provinceList.size()];
        // 为列表绑定数据源
        expandableListView.setAdapter(adapter);
        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                isOpen[groupPosition] = false;
            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                isOpen[groupPosition] = true;
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int j = 0; j < count; j++) {
                    if (j != groupPosition) {
                        expandableListView.collapseGroup(j);
                    }
                }
            }
        });
    }

    /**
     * 把一个省的对象转化为一个市的对象
     */
    public OfflineMapCity getCicy(OfflineMapProvince aMapProvince) {
        OfflineMapCity aMapCity = new OfflineMapCity();
        aMapCity.setCity(aMapProvince.getProvinceName());
        aMapCity.setSize(aMapProvince.getSize());
        aMapCity.setCompleteCode(aMapProvince.getcompleteCode());
        aMapCity.setState(aMapProvince.getState());
        aMapCity.setUrl(aMapProvince.getUrl());
        return aMapCity;
    }

    final ExpandableListAdapter adapter = new BaseExpandableListAdapter() {

        @Override
        public int getGroupCount() {
            return provinceList.size();
        }

        /**
         * 获取一级标签内容
         */
        @Override
        public Object getGroup(int groupPosition) {
            return provinceList.get(groupPosition).getProvinceName();
        }

        /**
         * 获取一级标签的ID
         */
        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        /**
         * 获取一级标签下二级标签的总数
         */
        @Override
        public int getChildrenCount(int groupPosition) {
            return cityMap.get(groupPosition).size();
        }

        /**
         * 获取一级标签下二级标签的内容
         */
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return cityMap.get(groupPosition).get(childPosition).getCity();
        }

        /**
         * 获取二级标签的ID
         */
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        /**
         * 指定位置相应的组视图
         */
        @Override
        public boolean hasStableIds() {
            return true;
        }

        /**
         * 对一级标签进行设置
         */
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            TextView group_text;
            if (convertView == null) {
                convertView = RelativeLayout.inflate(getBaseContext(), R.layout.sg_offlinemap_group, null);
            }
            group_text = convertView.findViewById(R.id.group_text);
            group_text.setText(provinceList.get(groupPosition).getProvinceName());
            return convertView;
        }

        /**
         * 对一级标签下的二级标签进行设置
         */
        @Override
        public View getChildView(final int groupPosition2, final int childPosition2,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolder holder;
            OfflineMapCity mapCity = cityMap.get(groupPosition2).get(childPosition2);
            if (convertView == null) {
                convertView = RelativeLayout.inflate(getBaseContext(), R.layout.sg_offlinemap_child, null);
                holder = new ViewHolder(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.cityDown.setTag(mapCity);
            BigDecimal b = new BigDecimal(mapCity.getSize() / (1024 * 1024f));
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            holder.cityName.setText(mapCity.getCity());
            holder.citySize.setText(f1 + "MB");
            holder.cityDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downloadMap((TextView) v);
                }
            });
            for (OfflineMapCity city : cityList) {
                if (city.getCity().equals(mapCity.getCity())) {
                    if (city.getState() == OfflineMapStatus.SUCCESS) {
                        holder.cityDown.setText("已下载");
                    } else if (city.getState() == OfflineMapStatus.LOADING) {
                        holder.cityDown.setText("下载" + completeCode + "%");
                    } else if (city.getState() == OfflineMapStatus.UNZIP) {
                        holder.cityDown.setText("解压" + completeCode + "%");
                    } else {
                        holder.cityDown.setText("下载");
                    }
                    break;
                }else {
                    holder.cityDown.setText("下载");
                }
            }
            return convertView;
        }

        class ViewHolder {
            TextView cityName;
            TextView citySize;
            TextView cityDown;

            public ViewHolder(View view) {
                view.setTag(this);
                cityName = view.findViewById(R.id.city_name);
                citySize = view.findViewById(R.id.city_size);
                cityDown = view.findViewById(R.id.city_down);
            }
        }

        /**
         * 当选择子节点的时候，调用该方法
         */
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    };

    private void downloadMap(TextView v) {
        String trim = v.getText().toString().trim();
        if (trim.equals("下载")) {
            try {
                downloadcity((OfflineMapCity) v.getTag());
            } catch (AMapException e) {
                T.showShort(context, e.getMessage());
            }
        }
    }

    //city
    private void downloadcity(OfflineMapCity mapCity) throws AMapException {
        if (cityList.isEmpty()) {
            amapManager.downloadByCityName(mapCity.getCity());
            cityList.add(0, mapCity);
        } else {
            if (cityList.get(0).getState() == 4) {
                amapManager.downloadByCityName(mapCity.getCity());
                cityList.add(0, mapCity);
            } else {
                T.showShort(context, "请稍后下载");
            }
        }
    }

    /**
     * 离线地图下载回调方法
     */
    @Override
    public void onDownload(int status, int completeCode2, String downName) {
        switch (status) {
            case OfflineMapStatus.SUCCESS:
                changeOfflineMapTitle(OfflineMapStatus.SUCCESS);
                SPUtils.put(context, cityKey, JSON.toJSONString(cityList));
                break;
            case OfflineMapStatus.LOADING:
                completeCode = completeCode2;
                changeOfflineMapTitle(OfflineMapStatus.LOADING);
                break;
            case OfflineMapStatus.UNZIP:
                completeCode = completeCode2;
                changeOfflineMapTitle(OfflineMapStatus.UNZIP);
                break;
            case OfflineMapStatus.WAITING:
                break;
            case OfflineMapStatus.PAUSE:
                break;
            case OfflineMapStatus.STOP:
                break;
            case OfflineMapStatus.ERROR:
                break;
            default:
                break;
        }
        ((BaseExpandableListAdapter) adapter).notifyDataSetChanged();
    }

    @Override
    public void onCheckUpdate(boolean b, String s) {
        try {
            amapManager.updateOfflineCityByName(s);
        } catch (AMapException e) {
            T.showShort(context, "更新失败:" + s);
        }
    }

    @Override
    public void onRemove(boolean b, String s, String s1) {
//        amapManager.remove("");
    }

    /**
     * 更改离线地图下载状态文字
     */
    private void changeOfflineMapTitle(int status) {
        cityList.get(0).setState(status);
    }

    @Override
    protected void onDestroy() {
        amapManager.destroy();
        super.onDestroy();
    }

}
